package com.gmlive.common.sample.widgets

import android.graphics.Canvas
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.gmlive.common.sample.databinding.ActivityRecyclerViewDemoBinding
import com.gmlive.common.sample.databinding.RecyclerGridItemBinding
import com.gmlive.common.ui.app.IkCompatActivity
import com.gmlive.common.ui.app.annotation.Immerse
import com.gmlive.common.ui.util.DisplayHelper
import com.gmlive.recyclerview.gridpager.GridPagerSnapHelper
import kotlin.random.Random

/**
 * @Author svenj
 * @Date 2021/1/22
 * @Email svenjzm@gmail.com
 */
@Immerse(fitSystemWindows = true)
class RecyclerViewActivity : IkCompatActivity() {

    private lateinit var mAdapter: RecyclerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val viewBinding = ActivityRecyclerViewDemoBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)

        val recyclerView = viewBinding.recycleView
        recyclerView.setHasFixedSize(true)
        recyclerView.addItemDecoration(ItemDivider())
        recyclerView.layoutManager = GridLayoutManager(this, 2,
                RecyclerView.HORIZONTAL, false)

        val items = transformData(createDataSource(), 2, 4)
        GridPagerSnapHelper().apply {
            setRow(2)
            setColumn(4)
            attachToRecyclerView(recyclerView)
        }

        mAdapter = RecyclerAdapter(BeanDiffCallback())
        recyclerView.adapter = mAdapter
        mAdapter.submitList(items)

        val indicator = viewBinding.indicator
        indicator.setPageColumn(4)
        indicator.setRecyclerView(recyclerView)

//        viewBinding.deleteButton.setOnClickListener {
//            val newList = transformData(randomRemove(), 2, 4)
//
//            mAdapter.submitList(newList)
//        }
    }

    inner class RecyclerAdapter(diffCallback: BeanDiffCallback) : ListAdapter<ItemBean?, RecyclerViewHolder>(diffCallback) {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
            val binding = RecyclerGridItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)

            return RecyclerViewHolder(binding)
        }

        override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
            val item = getItem(position)
            if (item != null) {
                holder.itemView.isVisible = true
                holder.icon.load(item.iconUrl)
                holder.name.text = item.nameText
            } else {
                holder.itemView.isVisible = false
            }
        }
    }

    private fun randomRemove(): List<ItemBean> {
        return createDataSource().apply {
            val index = Random.nextInt(0, size)
            removeAt(index)
        }
    }

    inner class BeanDiffCallback : DiffUtil.ItemCallback<ItemBean?>() {
        override fun areItemsTheSame(oldItem: ItemBean, newItem: ItemBean): Boolean {
            return oldItem.nameText == newItem.nameText
        }

        override fun areContentsTheSame(oldItem: ItemBean, newItem: ItemBean): Boolean {
            return oldItem.iconUrl == newItem.iconUrl
        }
    }

    inner class RecyclerViewHolder(binding: RecyclerGridItemBinding) : RecyclerView.ViewHolder(binding.root) {
        val icon: ImageView = binding.ivIcon
        val name: TextView = binding.tvName

        init {
            val screenWidth = DisplayHelper.getScreenWidth(itemView.context)
            val itemWidth = (screenWidth.toFloat() / 4 + 0.5).toInt()
            val itemHeight = DisplayHelper.dpToPx(110)
            ViewGroup.LayoutParams(itemWidth, itemHeight).let {
                itemView.layoutParams = it
            }
        }
    }

    private fun createDataSource(): MutableList<ItemBean> {
        return mutableListOf<ItemBean>().apply {
            add(ItemBean("https://imgky.hnyapu.cn/MTU1NzEzMjQ4NTgyNiMyMTAjcG5n.png", "爆音玫瑰"))
            add(ItemBean("https://media.xiangshengclub.com/MTYxMDYyMzQ4NTg1NCMgMzIjcG5n.png", "小k百宝箱"))
            add(ItemBean("http://imgtx.ikstatic.cn/MTU4NzM2MjA3OTc0OCM4NzIjcG5n.png", "白马王子"))
            add(ItemBean("https://media.xiangshengclub.com/MTYxMTAzMzQyOTE1NiM2NjkjcG5n.png", "水瓶座星雨"))
            add(ItemBean("https://media.xiangshengclub.com/MTYxMDE4NzM2Mjg2NSMgOTEjcG5n.png", "互动"))
            add(ItemBean("https://media.xiangshengclub.com/MTYxMDE4NzQ5MDAxMCMzMjcjcG5n.png", "点歌"))
            add(ItemBean("https://media.xiangshengclub.com/MTYxMDE4NzcyMzU2MiMzMDIjcG5n.png", "双费"))
            add(ItemBean("https://media.xiangshengclub.com/MTU5ODM0OTU2NzQwOCM2MzYjcG5n.png", "星座守护"))
            add(ItemBean("https://imgky.hnyapu.cn/MTU1NzEzNzc1MzMxNSMxOTcjcG5n.png", "罗马假日"))
            add(ItemBean("http://imgtx.ikstatic.cn/MTU4NzYyNDMzMjY1NyM1NzkjcG5n.png", "伴你野餐"))
            add(ItemBean("http://imgtx.ikstatic.cn/MTU4NTI3Njg4OTgzOSM2ODkjcG5n.png", "牧场恋曲"))
            add(ItemBean("http://imgtx.ikstatic.cn/MTU4NzczNTgwMjgzMCMgODcjcG5n.png", "精灵小鹿"))
        }
    }

    /**
     * 将原始数据转换为网格分页数据源
     */
    private fun transformData(items: List<ItemBean>, row: Int, column: Int): List<ItemBean?> {
        val pagerList = mutableListOf<ItemBean?>()

        val size = items.size
        val pageCount = row * column

        val traverseCount = when {
            size < pageCount -> {
                pageCount;
            }
            size % pageCount == 0 -> {
                size;
            }
            else -> {
                (size / pageCount + 1) * pageCount;
            }
        }

        for (i in 0 until traverseCount) {
            val pre = i / pageCount
            val divisor = i % pageCount
            var index = -1
            index = if (divisor % row == 0) {
                //even
                divisor / 2
            } else { //odd
                column + divisor / 2
            }

            //this is very important
            index += pre * pageCount
            if (index in 0 until size) {
                pagerList.add(items[index])
            } else {
                pagerList.add(null)
            }
        }

        return pagerList
    }

    data class ItemBean(
            val iconUrl: String,
            val nameText: String
    )

    inner class ItemDivider : RecyclerView.ItemDecoration() {
        private val paint = Paint().apply {
            color = 0x1FFFFFFF
        }

        override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
            val childCount = parent.childCount
            for (i in 0 until childCount) {
                val childView = parent.getChildAt(i)
                if (childView.isVisible) {
                    val x = childView.x
                    val y = childView.y
                    val width = childView.width
                    val height = childView.height
                    c.drawLine(x, y, x + width, y, paint)
                    c.drawLine(x, y, x, y + height, paint)
                    c.drawLine(x + width - 1, y, x + width - 1, y + height, paint)
                    c.drawLine(x, y + height - 1, x + width, y + height - 1, paint)
                }
            }
            super.onDraw(c, parent, state)
        }
    }
}